package top.lingkang.websocketlivechrome.nt;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler;
import io.netty.handler.ssl.SslContext;

public class MyWebSocketServerInitializer extends ChannelInitializer<SocketChannel> {

    private static final String WEBSOCKET_PATH = "/ws";

    private final SslContext sslCtx;

    public MyWebSocketServerInitializer(SslContext sslCtx) {
        this.sslCtx = sslCtx;
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        //是否开启 https
        if (sslCtx != null) {
            pipeline.addLast(sslCtx.newHandler(ch.alloc()));
        }

        //websocket基于http协议，所以用http解码器
        pipeline.addLast(new HttpServerCodec());

        //不能超过string的大小
        pipeline.addLast(new HttpObjectAggregator(65536));

        //鉴权处理 WebSocketServerProtocolHandler 需要开启 checkStartsWith
        pipeline.addLast(new MyWebsocketAuthHandler());

        //默认配置wensocket
        pipeline.addLast(new WebSocketServerCompressionHandler());

        //url参数鉴权的关键：匹配参数 checkStartsWith
        // WebSocketServerProtocolHandler(String websocketPath, String subprotocols,boolean allowExtensions, int maxFrameSize,
        // boolean allowMaskMismatch, boolean checkStartsWith)
        pipeline.addLast(new WebSocketServerProtocolHandler(
                WEBSOCKET_PATH, //路径
                null,
                true,
                Integer.MAX_VALUE, //最大处理数据内容
                false,  //掩码加密
                true //允许 websocketPath 路径匹配，否则走全匹配，例如 websocketPath=/ws request=/ws?user=zhangsan 将匹配不上，无法处理
        ));

        //websocket 处理
        pipeline.addLast(new MyWebSocketFrameHandler());
    }
}
